package com.hnqcgczy.dao.imp;

import com.hnqcgczy.dao.IUserDao;
import com.hnqcgczy.db.MyTransaction;
import com.hnqcgczy.vo.TUser;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements IUserDao {
    //事务
    private MyTransaction myTransaction;
    public UserDaoImpl(MyTransaction myTransaction){
        this.myTransaction=myTransaction;
    }

    @Override
    public boolean getUserByTuId(String tuId) throws SQLException {
        // 获取连接
        Connection conn=myTransaction.getConn();
        //编写sql语句
        String sql ="select * from t_user where tu_id = ?";
        //创建执行对象
        PreparedStatement ps=conn.prepareStatement(sql);
        //给？赋值（绑定参数）
        ps.setString(1,tuId);
        //执行sql语句，返回结果集
        ResultSet rs=ps.executeQuery();
        //定义返回结果变量
        boolean flag=false;
        while(rs.next()){
            flag=true;
        }
        //释放资源
        if(rs!=null){
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }
        //返回方法结果
        return flag;
    }

    @Override
    public boolean reg(TUser user) throws SQLException {
       //获取连接
        Connection conn=myTransaction.getConn();
        //编写sql语句
        String sql ="insert into t_user(tu_id,tu_password,tu_status) values(?,?,1)";
        //创建执行对象
        PreparedStatement ps=conn.prepareStatement(sql);
        //给？赋值
        ps.setString(1,user.getTuId());
        ps.setString(2,user.getTuPassword());
        //执行sql语句
        int i= ps.executeUpdate();
        //返回
        return i>0;
    }

    @Override
    public boolean login(String id, String password) throws SQLException {
        //获取连接
        Connection conn=myTransaction.getConn();
        //编写SQL
        String sql="select * from t_user where tu_id=? and tu_password=?";
        //创建执行对象
        PreparedStatement ps=conn.prepareStatement(sql);
        //给？赋值
        ps.setString(1,id);
        ps.setString(2,password);
        //执行SQL获得返回结果集
        ResultSet rs=ps.executeQuery();
        boolean flag=false;
        while(rs.next()){
            flag=true;
        }
        return flag;
    }

    public static void main(String[] args) {
        TUser user=new TUser();
        user.setTuId("zhangsan");
        user.setTuPassword("123456");
        try {
            new UserDaoImpl(new MyTransaction(true)).reg(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
